package com.wlit;

import io.netty.buffer.ByteBufUtil;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;


public class DataBuilder {

    private static byte[] accountAndPwd(String account,String password) throws Exception{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        String account = "310";
//        String password = "01234";
        byte[] accountBytes = account.getBytes(StandardCharsets.US_ASCII);
        byte[] passwordBytes = password.getBytes(StandardCharsets.US_ASCII);

        baos.write(accountBytes.length);
        baos.write(accountBytes);
        baos.write(passwordBytes.length);
        baos.write(passwordBytes);
        return baos.toByteArray();
    }

    public static void createData() throws Exception{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeByte(0xff);
        dos.writeByte(0x0c);
        byte[] data = accountAndPwd("tech310","weilexinxi310");
        dos.writeByte(data.length+4);
        dos.write(data);
        dos.writeByte(0xee);
        dos.flush();
        byte[] bytes = baos.toByteArray();
        System.out.println(ByteBufUtil.hexDump(bytes));
    }


    private static void createIpAddress(String ip,Integer port) throws Exception{
        byte[] data = buildIpAddr(ip,port);
        byte checksum = 0x00; // 初始化校验位
        for (byte b : data) {
            checksum ^= b; // 对每个字节进行异或操作
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(data);
        baos.write(checksum);
        byte[] result =  baos.toByteArray();
        System.out.println(ByteBufUtil.hexDump(result).toUpperCase());
    }

    private static byte[] buildIpAddr(String ip, Integer port) throws Exception{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeByte(0x0B);
        dos.writeByte(0xA4);

        InetAddress address = InetAddress.getByName(ip);
        byte[] bb  = address.getAddress();
        dos.write(bb);
        //补充够6位的ip地址
        dos.writeByte(0x00);
        dos.writeByte(0x00);
        //端口
        dos.writeShort(port);

        dos.flush();
        return baos.toByteArray();
    }




    public static void main(String[] args) throws Exception{
        createIpAddress("192.168.0.201", 9220);

       // createData();
    }
}
